package com.thx.information.service;

import com.thx.common.service.BaseManager;
import com.thx.information.dao.InfoVoteItemDao;
import com.thx.information.model.InfoVoteItem;
import com.thx.information.model.InfoVoteLog;
import com.thx.information.view.VoteItemLogView;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class InfoVoteItemService extends BaseManager<InfoVoteItem> {

  private static final Logger logger = LoggerFactory.getLogger(InfoVoteItemService.class);

  @Autowired
  private InfoVoteItemDao infovoteDao;

  @Autowired
  private InfoVoteLogService infoVoteLogService;

  public List<InfoVoteItem> queryVotes(Long infoId) {
    return infovoteDao.findAllByInfoId(infoId);
  }

  /**
   * 根据多个投票项字符串删除投票项,分隔符为','.
   * 
   * @param voteitemids 多个投票项字符串
   */
  @Transactional(readOnly = false)
  public void deleteByVoteItemIds(String voteitemids) {
    String[] ids = StringUtils.split(voteitemids, ",");
    if (ids != null && ids.length != 0) {
      for (int i = 0; i < ids.length; i++) {
        infovoteDao.delete(NumberUtils.toLong(ids[i]));
      }
    }
  }

  /**
   * 根据信息id删除所有投票选项信息
   * 
   * @param infoId 信息id,不能为空
   */
  @Transactional(readOnly = false)
  public void deleteByInfoId(Long infoId) {
    infovoteDao.deleteByInfoId(infoId);
  }


  /**
   * 查询投票信息.
   * 
   * @param infoId
   * @return
   */
  public List<VoteItemLogView> queryVoteItemLogView(Long infoId) {
    List<VoteItemLogView> v = new ArrayList<VoteItemLogView>();
    List<InfoVoteItem> votesList = infovoteDao.findAllByInfoId(infoId);
    if (votesList != null) {
      for (InfoVoteItem a : votesList) {
        VoteItemLogView view = new VoteItemLogView();
        view.setInfoVoteItem(a);
        view.setOptionName(a.getOptionName());
        view.setVoteItemId(a.getVoteItemId());
        List<InfoVoteLog> logs = infoVoteLogService.queryByItemId(a.getVoteItemId());
        Long count = infoVoteLogService.queryCountByItemId(a.getVoteItemId());
        view.setInfoVoteLog(logs);
        view.setVoteTotal(count);
        v.add(view);
      }
    }
    return v;
  }

}
